package com.ljh.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import com.ljh.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

/**
 * @author: Themberfue
 * @date: 2025/2/20 22:03
 * @description:
 */
@RequestMapping("/captcha")
@RestController
public class CaptchaController {
    @Autowired
    CaptchaProperties captchaProp;

    private static final Long VALID_TIME = 60 * 1000L;

    @RequestMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response) {
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-Cache");

        try {
            ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(captchaProp.getWidth(), captchaProp.getHeight());
            String code = captcha.getCode();
            System.out.println(code);
            session.setAttribute(captchaProp.getSession().getKey(), code);
            session.setAttribute(captchaProp.getSession().getDate(), new Date());
            captcha.write(response.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public boolean check(String captcha, HttpSession session) {
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }

        if (session == null) {
            return false;
        }

        // 校验验证码
        String code = (String) session.getAttribute(captchaProp.getSession().getKey());
        Date date = (Date) session.getAttribute(captchaProp.getSession().getDate());

        if (date == null) {
            return true;
        }
        return captcha.equalsIgnoreCase(code) && System.currentTimeMillis() - date.getTime() <= VALID_TIME;
    }
}
